package com.caigou.app

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.caigou.app.viewmodel.MainViewModel
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bean.UserBean
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.Logger
import com.caigou.comm.base.utils.SessionUtil
import com.caigou.library.statusbar.NotchScreenManager
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/09/13
 */
@AndroidEntryPoint
class WelcomeActivity : AppCompatActivity() {

    companion object {
        //        private const val CODE_GO_INIT = 0x000003E8
        private const val CODE_GO_MAIN_ACTIVITY = 0x000003E9
    }

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
//                CODE_GO_INIT -> goInit()
                CODE_GO_MAIN_ACTIVITY -> goMainActivity()
            }
        }
    }


//    private var autoLauncher = false
    private val mainViewModel: MainViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        NotchScreenManager.getInstance().setDisplayInNotch(this)
        window.setBackgroundDrawableResource(R.drawable.caigou_welcome)
        // 检查缓存的账号信息并自动登录
        observe(mainViewModel.autoLauncherLiveData, ::handleAutoLogin)

        XXPermissions.with(this)
            .permission(Permission.CAMERA)
            .permission(Permission.Group.STORAGE)
            // 设置权限请求拦截器（局部设置）
            //.interceptor(new PermissionInterceptor())
            // 设置不触发错误检测机制（局部设置）
            //.unchecked()
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, all: Boolean) {
                    if (!all) {
                        showToast("获取部分权限成功，但部分权限未正常授予，可能影响部分功能使用")
                    }
                    doAutoLogin()
//                    handler.sendEmptyMessageDelayed(CODE_GO_INIT, 400)
                }

                override fun onDenied(permissions: MutableList<String>, never: Boolean) {
                    showToast("获取存储和相机权限失败，可能影响部分功能使用")
                    doAutoLogin()
//                    if (never) {
//                        showToast("被永久拒绝授权，请手动授予存储和相机权限")
//                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
//                        XXPermissions.startPermissionActivity(this@WelcomeActivity, permissions)
//                    } else {

//                        handler.sendEmptyMessageDelayed(CODE_GO_INIT, 400)
//                    }
                }
            })
    }

    private fun doAutoLogin() {
        val session = SessionUtil.getSession()
        if (session == null) {
            handler.sendEmptyMessageDelayed(CODE_GO_MAIN_ACTIVITY, 1000)
        } else {
            if (!TextUtils.isEmpty(session.mobile) && !TextUtils.isEmpty(session.password)) {
                mainViewModel.autoLauncher(session.mobile, session.password)
            } else {
                handler.sendEmptyMessageDelayed(CODE_GO_MAIN_ACTIVITY, 1000)
            }
        }
    }

//    private fun goInit() {
//        val animation = AlphaAnimation(0.3f, 1.0f)
//        animation.duration = 1500
//        animation.setAnimationListener(object : Animation.AnimationListener {
//            override fun onAnimationStart(animation: Animation?) {
//            }
//
//            override fun onAnimationEnd(animation: Animation?) {
//                if (!autoLauncher) {
//                    handler.sendEmptyMessage(CODE_GO_GAME_ACTIVITY)
//                }
//            }
//
//            override fun onAnimationRepeat(animation: Animation?) {
//            }
//        })
//        setView(animation)
//    }

    private fun handleAutoLogin(result: Resource<UserBean>) {
        when (result) {
            is Resource.Loading -> {

            }
            is Resource.DataError -> {
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("用户登录异常，请重新登录")
                    handler.sendEmptyMessage(CODE_GO_MAIN_ACTIVITY)
                }
            }
            is Resource.Success -> {
                if (result.data == null) {
                    return
                }
                AppBackgroundInfo.instance.hasLogin = true
                AppBackgroundInfo.instance.userBean = result.data
                handler.sendEmptyMessageDelayed(CODE_GO_MAIN_ACTIVITY, 1000)
            }
        }
    }

    private fun goMainActivity() {
        Logger.i("goActivity -> action = ${this.packageName}")
        startActivity(Intent(this.packageName))
        finish()
    }


//    private fun setView(animation: Animation) {
//        val id = resources.getIdentifier("caigou_welcome", "drawable", packageName)
//
//        if (id == 0) {
//            handler.sendEmptyMessage(CODE_GO_GAME_ACTIVITY)
//            return
//        }
//
//        val layout = LinearLayout(this)
//        layout.setBackgroundResource(id)
//        layout.animation = animation
//        setContentView(layout)
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == XXPermissions.REQUEST_CODE) {
            if (XXPermissions.isGranted(this, Permission.CAMERA) && XXPermissions.isGranted(this, Permission.Group.STORAGE)) {
//                handler.sendEmptyMessageDelayed(CODE_GO_INIT, 400)
                doAutoLogin()
            } else {
                showToast("获取存储和相机权限失败，可能影响部分功能使用")
//                handler.sendEmptyMessageDelayed(CODE_GO_INIT, 400)
                doAutoLogin()
            }
        }
    }
}